package com.qsd.doc4jsimpple;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart;
import org.docx4j.wml.*;
import org.docx4j.wml.Numbering.Num;

public class MultipleNumberingDefinitionsExample2 {

    public static void main(String[] args) throws Exception{
        try {
            // 创建一个新的Word文档对象
            WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();

            // 创建第一个NumberingDefinitionsPart（阿拉伯数字编号）
            NumberingDefinitionsPart numberingPart1 = createArabicNumberingDefinitionsPart();
            wordPackage.getMainDocumentPart().addTargetPart(numberingPart1);

            // 创建段落并应用第一个编号定义
            P paragraph1 = createParagraphWithNumbering("这是第一个编号段落1", 1, numberingPart1);
            wordPackage.getMainDocumentPart().addObject(paragraph1);
            P paragraph2 = createParagraphWithNumbering("这是第一个编号段落2", 1, numberingPart1);
            wordPackage.getMainDocumentPart().addObject(paragraph2);

            // 创建第二个NumberingDefinitionsPart（字母编号）
            NumberingDefinitionsPart numberingPart2 = createLetterNumberingDefinitionsPart();
            wordPackage.getMainDocumentPart().addTargetPart(numberingPart2);

            // 创建段落并应用第二个编号定义
            P paragraph3 = createParagraphWithNumbering("这是第二个编号段落1", 2, numberingPart2);
            wordPackage.getMainDocumentPart().addObject(paragraph3);
            P paragraph4 = createParagraphWithNumbering("这是第二个编号段落2", 2, numberingPart2);
            wordPackage.getMainDocumentPart().addObject(paragraph4);

            // 保存文档
            wordPackage.save(new File("multiple_numbering_example_fixed.docx"));
            System.out.println("文档已成功创建！");
        } catch (Docx4JException e) {
            e.printStackTrace();
        }
    }

    // 创建阿拉伯数字编号的NumberingDefinitionsPart
    private static NumberingDefinitionsPart createArabicNumberingDefinitionsPart() throws Exception{
        NumberingDefinitionsPart numberingPart = new NumberingDefinitionsPart();

        // 创建AbstractNum（抽象编号定义），设置为阿拉伯数字编号样式
        Numbering.AbstractNum abstractNum = new Numbering.AbstractNum();
        abstractNum.setAbstractNumId(BigInteger.valueOf(1));

        // 设置编号级别，这里简单设置一级编号
        Lvl lvl = new Lvl();
        lvl.setIlvl(BigInteger.valueOf(0));
        NumFmt numFmt = new NumFmt();
        numFmt.setVal(NumberFormat.DECIMAL);
        lvl.setNumFmt(numFmt); // 阿拉伯数字格式

        Lvl.LvlText lvltext = new Lvl.LvlText();
        //表示显示第一级编号，后面跟一个“.”
        //  lvltext.setVal("\u2022");
        lvltext.setVal("%1.");// 编号文本格式
        lvl.setLvlText(lvltext);
        abstractNum.getLvl().add(lvl);

        // 创建Numbering并添加AbstractNum
        Numbering numbering = Context.getWmlObjectFactory().createNumbering();
        Num num = Context.getWmlObjectFactory().createNumberingNum();
        num.setNumId(BigInteger.valueOf(1));
        Numbering.Num.AbstractNumId abstractNumId = new Numbering.Num.AbstractNumId();
        abstractNumId.setVal(abstractNum.getAbstractNumId());
        num.setAbstractNumId(abstractNumId);
        numbering.getNum().add(num);

        try {
            numberingPart.setJaxbElement(numbering);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return numberingPart;
    }

    // 创建字母编号的NumberingDefinitionsPart
    private static NumberingDefinitionsPart createLetterNumberingDefinitionsPart() throws Exception{
        NumberingDefinitionsPart numberingPart = new NumberingDefinitionsPart();

        // 创建AbstractNum（抽象编号定义），设置为字母编号样式
        Numbering.AbstractNum abstractNum = new Numbering.AbstractNum();
        abstractNum.setAbstractNumId(BigInteger.valueOf(2));

        // 设置编号级别，这里简单设置一级编号
        Lvl lvl = new Lvl();
        lvl.setIlvl(BigInteger.valueOf(0));
        NumFmt numFmt = new NumFmt();
        numFmt.setVal(NumberFormat.LOWER_LETTER);
        lvl.setNumFmt(numFmt); // 阿拉伯数字格式

        Lvl.LvlText lvltext = new Lvl.LvlText();
        //表示显示第一级编号，后面跟一个“.”
        //  lvltext.setVal("\u2022");
        lvltext.setVal("%1.");// 编号文本格式
        lvl.setLvlText(lvltext);
        abstractNum.getLvl().add(lvl);

        // 创建Numbering并添加AbstractNum
        Numbering numbering = Context.getWmlObjectFactory().createNumbering();
        Num num = Context.getWmlObjectFactory().createNumberingNum();
        num.setNumId(BigInteger.valueOf(2));
        Numbering.Num.AbstractNumId abstractNumId = new Numbering.Num.AbstractNumId();
        abstractNumId.setVal(abstractNum.getAbstractNumId());
        num.setAbstractNumId(abstractNumId);
        numbering.getNum().add(num);

        try {
            numberingPart.setJaxbElement(numbering);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return numberingPart;
    }

    // 创建带有指定编号定义的段落，重点改进了关联编号定义的部分
    private static P createParagraphWithNumbering(String textContent, int numId, NumberingDefinitionsPart numberingPart) {
        P paragraph = Context.getWmlObjectFactory().createP();

        // 创建一个运行（包含文本的最小单元）
        R run = Context.getWmlObjectFactory().createR();
        Text text = Context.getWmlObjectFactory().createText();
        text.setValue(textContent);
        run.getContent().add(text);

        // 将运行添加到段落
        paragraph.getContent().add(run);

        // 设置段落的编号属性，应用指定的编号定义
        org.docx4j.wml.PPr pPr = Context.getWmlObjectFactory().createPPr();
        org.docx4j.wml.PPrBase.NumPr numPr = Context.getWmlObjectFactory().createPPrBaseNumPr();
        PPrBase.NumPr.NumId numIdElement = Context.getWmlObjectFactory().createPPrBaseNumPrNumId();
        numIdElement.setVal(BigInteger.valueOf(numId));
        numPr.setNumId(numIdElement);


        PartName partName = numberingPart.getPartName();
        String relationshipId = numberingPart.getSourceRelationships().get(0).getId();
       // System.out.println("relationshipId: " + relationshipId);
        // 改进：通过获取正确的关系部件标识来关联到对应的NumberingDefinitionsPart
      //  numPr.setNumId(numberingPart.getRelationshipsPart().getRelationshipByID("2"));
        pPr.setNumPr(numPr);
        paragraph.setPPr(pPr);

        return paragraph;
    }
}
